﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.DAO;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;
using br.com.SistemaChamados.Constants;

public partial class Pages_Common_CallInsert : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillDdlCallCategory();
            FillDdlUnit();
            FillData();
        }
    }

    private void FillDdlCallCategory()
    {
        CallCategoryController callCategoryController = new CallCategoryController();
        ddlCallCategory.DataSource = callCategoryController.GetCallCategories();
        ddlCallCategory.DataTextField = "Description";
        ddlCallCategory.DataValueField = "Id";
        ddlCallCategory.DataBind();
        ddlCallCategory.Items.Insert(0, "Selecione");
    }

    private void FillDdlUnit()
    {
        UnitController unitController = new UnitController();
        ddlUnit.DataSource = unitController.GetUnits();
        ddlUnit.DataTextField = "Name";
        ddlUnit.DataValueField = "Id";
        ddlUnit.DataBind();
        ddlUnit.Items.Insert(0, "Selecione");
    }

    private void FillData()
    {
        // string id = Session["UserIdToGetUnit"].ToString();
        User user = new User();
        UserController userController = new UserController();
        //annex.Id = Convert.ToInt32(id);
        user.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN].ToString());
        user = userController.GetUser(user);
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        sector.Id = user.Sector.Id;
        sector = sectorController.GetSector(sector);
        br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
        unit.Id = sector.Unit.Id;
        try
        {
            MatchDdlUnitValue(unit);
            FillDdlSector();
            MatchDdlSectorValue(sector);
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na carga dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void MatchDdlUnitValue(br.com.SistemaChamados.Model.Unit unit)
    {
        ListItem listUnit = ddlUnit.Items.FindByValue(Convert.ToString(unit.Id));

        for (int i = 0; i < ddlUnit.Items.Count; i++)
        {
            ddlUnit.Items[i].Selected = false;
        }
        if (listUnit != null)
        {
            listUnit.Selected = true;
        }
        else
        {
            ddlUnit.Items[0].Selected = true;
        }
    }

    private void FillDdlSector()
    {
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
        if (Convert.ToInt32(ddlUnit.SelectedIndex) != 0)
        {
            unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
            sector.Unit = unit;
            ddlSector.DataSource = sectorController.GetSectorsByUnit(sector.Unit);
            ddlSector.DataTextField = "Description";
            ddlSector.DataValueField = "Id";
            ddlSector.DataBind();
            ddlSector.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlSector();
        }
    }

    private void ClearDdlSector()
    {
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        ddlSector.Items[0].Selected = true;
        ddlSector.DataSource = "";
        ddlSector.DataBind();
    }

    private void MatchDdlSectorValue(Sector sector)
    {
        ListItem listSector = ddlSector.Items.FindByValue(Convert.ToString(sector.Id));
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        if (listSector != null)
        {
            listSector.Selected = true;
        }
        else
        {
            ddlSector.Items[0].Selected = true;
        }
    }

    protected void btnCallInsert_Click(object sender, EventArgs e)
    {
        Call call = new Call();
        CallController callController = new CallController();
        int? callId = null;
        try
        {
            call.ProblemDescription = txbProblemDescription.Text;
            //string userId = Session["userLoggedIn"].ToString();
            string userId = Convert.ToString(Session[UserConstants.SESSION_USER_LOGGED_IN].ToString());
            callId = Convert.ToInt32(callController.GetCallId());
            call.Id = callId.Value;
            User userOpen = new User();
            userOpen.Id = Convert.ToInt32(userId);
            call.UserOpen = userOpen;
            CallSubCategory callSubCategory = new CallSubCategory();
            callSubCategory.Id = Convert.ToInt32(ddlCallSubCategory.SelectedValue);
            call.CallSubCategory = callSubCategory;
            Sector sector = new Sector();
            sector.Id = Convert.ToInt32(ddlSector.SelectedValue);
            call.Sector = sector;
            call.ProblemDescription = txbProblemDescription.Text;
            CallStatus callStatus = new CallStatus();
            callStatus.Id = 1;
            call.CallStatus = callStatus;
            if (callController.InsertCall(call) == EnumGenericState.GENERIC_STATE_SUCCESS)
            {
                if (InsertAnnex(callId.Value) != EnumGenericState.GENERIC_STATE_FAILED)
                {
                    Response.Write(@"<script language='javascript'>alert('Chamado cadastrado com sucesso!');</script>");
                    UserController userController = new UserController();
                    List<User> listAnalyst = userController.GetUsersByRole("ANALYST");
                    foreach (User user in listAnalyst)
                    {
                        string subject = "Foi aberto um novo chamado no sistema!";
                        string message = "Um novo chamado foi gerado no SysCall com a seguinte descrição: '" + call.ProblemDescription + "'. Encaminhar o chamado para a equipe técnica o mais rápido possível!";
                        EmailUtils.SendMail(user.EMail, subject, message);
                    }
                    User loggedUser = new br.com.SistemaChamados.Model.Common.User();
                    loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
                    loggedUser = userController.GetUser(loggedUser);
                    if (loggedUser != null)
                    {
                        string subjectUser = "Seu chamado está no sistema!";
                        string messageUser = "Seu chamado com a seguinte descrição '" + call.ProblemDescription + "' foi aberto no sistema. Aguarde atendimento.";
                        EmailUtils.SendMail(loggedUser.EMail, subjectUser, messageUser);
                    }
                    Response.Redirect("CallMain.aspx");
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o carregamento do anexo, por favor tente novamente!');</script>");
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o cadastro, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao abrir o chamado: <br>" + ex.Message + ".');</script>");
            call = null;
            callController = null;
        }
    }

    private bool validateCall()
    {
        bool isValid = false;
        if (Convert.ToInt32(ddlCallCategory.SelectedIndex) != 0)
        {
            if (Convert.ToInt32(ddlUnit.SelectedIndex) != 0)
            {
                if (Convert.ToInt32(ddlSector.SelectedIndex) != 0)
                {
                    if (Convert.ToInt32(ddlCallSubCategory.SelectedIndex) != 0)
                    {
                        int? callId;
                        CallController callController = new CallController();
                        callId = Convert.ToInt32(callController.GetCallId());
                        if (callId != null)
                        {
                            isValid = true;
                        }
                    }
                }
            }
        }
        return isValid;
    }

    private String RandomGenerator()
    {
        return SecurityUtils.generateRandonNumber().ToString();
    }

    private void FillDdlSubCategory()
    {
        CallSubCategoryController callSubCategoryController = new CallSubCategoryController();
        CallCategory callCategory = new CallCategory();
        CallSubCategory callSubCategory = new CallSubCategory();
        if (Convert.ToInt32(ddlCallCategory.SelectedIndex) != 0)
        {
            callCategory.Id = Convert.ToInt32(ddlCallCategory.SelectedValue);
            callSubCategory.CallCategory = callCategory;
            ddlCallSubCategory.DataSource = callSubCategoryController.GetCallSubCategoriesByCallCategory(callSubCategory);
            ddlCallSubCategory.DataTextField = "Description";
            ddlCallSubCategory.DataValueField = "Id";
            ddlCallSubCategory.DataBind();
            ddlCallSubCategory.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlCallSubCategory();
        }
    }

    private void ClearDdlCallSubCategory()
    {
        for (int i = 0; i < ddlCallSubCategory.Items.Count; i++)
        {
            ddlCallSubCategory.Items[i].Selected = false;
        }
        ddlCallSubCategory.Items[0].Selected = true;
        ddlCallSubCategory.DataSource = "";
        ddlCallSubCategory.DataBind();
    }

    private EnumGenericState InsertAnnex(int callId)
    {
        EnumGenericState resultAnnex = EnumGenericState.GENERIC_STATE_UNKNOW;
        string saveDir = @"Uploads\";
        string appPath = Request.PhysicalApplicationPath;
        if (fuAnnex.HasFile)
        {
            string fileName = Server.HtmlEncode(fuAnnex.FileName);
            string extension = (System.IO.Path.GetExtension(fileName)).ToLower();
            if ((extension == ".pdf") || (extension == ".jpg") || (extension == ".jpeg") || (extension == ".png") || (extension == ".bmp"))
            {
                int fileSize = fuAnnex.PostedFile.ContentLength;
                if (fileSize < 510000)
                {
                    string savePath = appPath + saveDir + Server.HtmlEncode(RandomGenerator() + extension);
                    while (System.IO.File.Exists(savePath))
                    {
                        savePath = appPath + saveDir +
                        Server.HtmlEncode(RandomGenerator() + extension);
                    }
                    fuAnnex.SaveAs(savePath);
                    if (System.IO.File.Exists(savePath))
                    {
                        Annex annex = new Annex();
                        AnnexController annexController = new AnnexController();
                        Call call = new Call();
                        call.Id = callId;
                        annex.Call = call;
                        annex.Description = savePath;
                        EnumCRUDState resultOperation = annexController.InsertAnnex(annex);
                        if (resultOperation == EnumCRUDState.SQL_SUCCESS)
                        {
                            resultAnnex = EnumGenericState.GENERIC_STATE_SUCCESS;
                        }
                        else
                        {
                            AnnexRemoval(savePath);
                            resultAnnex = EnumGenericState.GENERIC_STATE_FAILED;
                        }
                    }
                    else
                    {
                        resultAnnex = EnumGenericState.GENERIC_STATE_FAILED;
                    }
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('O arquivo deve ter tamanho máximo de 2 MB.');</script>");
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Somente arquivo com extensões pdf/jpg/jpeg/png são permitidos.');</script>");
            }
        }
        return resultAnnex;
    }

    private void AnnexRemoval(string savePath)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(savePath);
        try
        {
            file.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }

    protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlSector();
    }
    protected void ddlCallCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlSubCategory();
    }
}